package com.kangjia.api;

import java.io.IOException;
import java.util.Comparator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.kangjia.http.HttpParam;
import com.kangjia.http.HttpRequest;
import com.kangjia.http.HttpResponse;
import com.kangjia.jasckson.DataMapper;

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 康加接口抽象类实现,主要处理返回内容
 * 
 * @author sunshulin
 *
 */
@Slf4j
public abstract class AbstractApiImpl {

	protected DataMapper dataMapper = DataMapper.getInstance();
	@Autowired
	protected HttpRequest httpRequest;
	@Autowired
	protected JedisPool jedisPool;
	@Value("${kangjia.secret}")
	private String secret;

	/**
	 * http 响应结果处理方法
	 * 
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws JsonProcessingException
	 */
	public JsonNode handlerResponse(HttpResponse response, String field) throws JsonProcessingException, IOException {
		log.info("响应码={}, 返回结果={}", response.getRpc(), response.getResponse());
		if (response.getRpc() == 200) {
			String rtnStr = response.getResponse();
			JsonNode jsonNode = dataMapper.readTree(rtnStr);
			JsonNode rep = jsonNode.get("repCode");
			if (rep.asInt() == 200) {
				return jsonNode.get(field);
			}
		}
		return null;
	}

	/**
	 * 获取康加token
	 * 
	 * @return
	 */
	protected String getKangjiaToken() {
		Jedis jedis = jedisPool.getResource();
		String token = jedis.get("kangjia.token");
		jedis.close();
		return token;
	}

	/**
	 * 获取sign
	 * 
	 * @param params
	 * @return
	 */
	protected String getSign(List<HttpParam> params) {
		StringBuilder str = new StringBuilder();
		params.sort(new Comparator<HttpParam>() {
			public int compare(HttpParam o1, HttpParam o2) {
				String s1 = o1.getParam();
				String s2 = o2.getParam();
				return s1.compareTo(s2);
			}
		});
		for (HttpParam param : params) {
			str.append("&" + param.string());
		}
		String s = str.replace(0, 1, "").toString();
		log.info("参数 sign={}", s);
		HiiposmUtil util = new HiiposmUtil();
		return util.MD5Sign(s, secret);
	}
}
